package com.example.spring_mysql.excel

import com.alibaba.excel.EasyExcel
import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream


@Service
class TranslationService {
    @Throws(IOException::class)
    fun parse(file: MultipartFile): Map<String, MutableList<String>> {
//        val inputStream = file.inputStream
//        val excelReader = EasyExcel.read(inputStream).build()
//        val sheetList = excelReader.excelExecutor().sheetList()
//        for (sheet in sheetList) {
//            println("Sheet name: ${sheet.sheetName}, index: ${sheet.sheetNo}")
//        }
//        excelReader.finish()
        val rows: List<TranslationRow> = EasyExcel.read(
            file.inputStream, TranslationRow::class.java, null
        ).sheet("99真主名").headRowNumber(2).doReadSync()
        rows.forEach {
            println(it.arName)
        }
        val result: MutableMap<String, MutableList<String>> = HashMap()
        rows.forEachIndexed { index, translationRow ->
            addEntry(result, "values", "allah_${index + 1}_name", translationRow.enName)
//            addEntry(result, "values", "allah_${index + 1}_explanation", translationRow.enExplanation)
        }
        return result
    }

    private fun addEntry(map: MutableMap<String, MutableList<String>>, folder: String, key: String, value: String) {
        if (!map.containsKey(folder)) {
            map[folder] = ArrayList()
        }
        map[folder]!!.add(String.format("    <string name=\"%s\" translatable=\"false\">%s</string>", key, escapeXml(value)))
    }

    private fun escapeXml(value: String?): String {
        return value?.replace("&", "&amp;")?.replace("<", "&lt;")?.replace(">", "&gt;")
            ?.replace("\"", "\\\"")  // 👈 把 " 替换为 \"
            ?.replace("\'", "\\\'")?.replace("%@", "%s") ?: ""
//        return value?.replace("&", "&amp;")?.replace("<", "&lt;")?.replace(">", "&gt;")?.replace("\"", "&quot;")
//            ?.replace("'", "&apos;") ?.replace("%@", "%s") ?: ""
    }

    @Throws(IOException::class)
    fun buildZip(folderMap: Map<String, List<String>>): ByteArray {
        val zipOut = ByteArrayOutputStream()
        val zos = ZipOutputStream(zipOut)

        for ((folderName, lines) in folderMap) {
            val filePath = "$folderName/strings.xml"
            zos.putNextEntry(ZipEntry(filePath))

            zos.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n".toByteArray(Charsets.UTF_8))
            for (line in lines) {
                zos.write((line + "\n").toByteArray(Charsets.UTF_8))
            }
            zos.write("</resources>".toByteArray(Charsets.UTF_8))
            zos.closeEntry()
        }

        zos.close()
        return zipOut.toByteArray()
    }
}
